<template>
  <view class="container">
    <!-- 导航栏 -->
    <uni-nav-bar :fixed="true" background-color="#FFF" :border="false" status-bar left-icon="left" left-text="返回"
			title="编辑游记" @clickLeft="back" />

    <!-- 内容区域 -->
    <view class="content">
        <textarea
            class="content-input"
            placeholder="请输入游记内容..."
            v-model="content"
            maxlength="5000"
        />
    </view>

    <!-- 底部固定区域 -->
    <view class="bottom-area">
      <!-- 图片编辑区 -->
      <view class="photo-grid">
        <!-- <scroll-view class="scroll-view-horizontal" scroll-x="true" @scroll="scroll" scroll-left="120"> -->
          <view v-for="(photo, photoIndex) in photos" :key="photoIndex" class="photo-item">
            <image v-if="photo && photo.photo" class="photo-preview" :src="photo.photo" mode="aspectFill" />
            <image v-else-if="photo && photo.url" class="photo-preview" :src="photo.url" mode="aspectFill" />
            <view v-else class="photo-placeholder" @click="addPhoto(photoIndex)">
              <text class="plus-icon">+</text>
              <text class="upload-text">上传图片</text>
            </view>
            <view v-if="photo && photo.upload_progress" class="photo-progress">
              <text>{{photo.upload_progress}}</text>
            </view>
            <view v-if="photo" class="photo-delete" @click="removePhoto(photoIndex)">
              <text class="delete-icon">×</text>
            </view>
            
          </view>
        <!-- </scroll-view> -->
        </view>

      <!-- 按钮区域 -->
      <view class="action-buttons">
            <button type="default" class="cancel-btn" @tap="handleCancel">取消</button>
            <button type="primary" class="publish-btn" @tap="handlePublish" :disabled="!isChanged">发布</button>
        </view>
    </view>
  </view>
    
</template>
  
<script setup>
import { ref, onMounted, computed, watch } from 'vue';

const photos = ref([
  null
]);
const content = ref('');
var travel_id = "";
var travelData = {};
const isChanged = ref(false);

watch(content, (newVal) => {
  checkChanged();
});

function checkChanged() {
    if (!travelData || !travelData.report_content) {
        return false;
    }
    const contentChanged = content.value != travelData.report_content;
    const photosNeedAdd = [];
  const photosNeedDelete = [];
  // photos中，url不为空，且status为uploaded的，且在travelData.img_urls中不存在的，需要新增；
  photos.value.forEach(photo => {
    if (photo && photo.url && photo.status == "uploaded" && !travelData.img_urls.includes(photo.url)) {
      photosNeedAdd.push(photo.url);
    }
  });
  console.log("photosNeedAdd:", photosNeedAdd);
  //travelData.img_urls中存在的，但在photos中不存在的，需要删除；
  travelData.img_urls.forEach(url => {
    if (!photos.value.some(photo => photo && photo.url == url)) {
      photosNeedDelete.push(url);
    }
  });
  console.log("photosNeedDelete:", photosNeedDelete);
    const photosChanged = photosNeedAdd.length > 0 || photosNeedDelete.length > 0;
    console.log("checkChanged:", contentChanged, photosChanged);
    isChanged.value = contentChanged || photosChanged;
}


onMounted(() => {
    // 获取路由参数
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.options || {};
  travel_id = options.travel_id;
  console.log("travel_id:", travel_id);
    // const travel_id = uni.parseParams().travel_id;
  loadJournalDataById(travel_id);
});

function back() {
  uni.navigateBack();
}

function handleCancel() {
  uni.navigateBack();
}

function handlePublish() {

  if (content.value == "") {
    uni.showToast({
      title: '请输入游记内容',
      icon: 'none'
    });
    return;
  }
  console.log(content.value);
  console.log(photos.value);
  const photosNeedAdd = [];
  const photosNeedDelete = [];
  // photos中，url不为空，且status为uploaded的，且在travelData.img_urls中不存在的，需要新增；
  photos.value.forEach(photo => {
    if (photo && photo.url && photo.status == "uploaded" && !travelData.img_urls.includes(photo.url)) {
      photosNeedAdd.push(photo.url);
    }
  });
  console.log("photosNeedAdd:", photosNeedAdd);
  //travelData.img_urls中存在的，但在photos中不存在的，需要删除；
  travelData.img_urls.forEach(url => {
    if (!photos.value.some(photo => photo && photo.url == url)) {
      photosNeedDelete.push(url);
    }
  });
  console.log("photosNeedDelete:", photosNeedDelete);

  // 创建Promise数组来存储所有请求
  const promises = [];

  // 添加图片请求
  if (photosNeedAdd.length > 0) {
    console.log("添加图片请求");
    var addUrls = ''
    photosNeedAdd.forEach(url => {
        addUrls+=`&img_urls=${encodeURIComponent(url)}`;
    })
    promises.push(new Promise((resolve, reject) => {
      uni.request({
        url: `https://tushuoit.com/api/ju/travel_share/upload_imgs_url/by_id?id=${travelData.id}${addUrls}`,
        method: 'POST',
        success: resolve,
        fail: reject
      });
    }));
  }

  // 删除图片请求
  if (photosNeedDelete.length > 0) {
    console.log("删除图片请求");
    var deleteUrls = ''
    photosNeedDelete.forEach(url => {
        deleteUrls+=`&img_urls=${encodeURIComponent(url)}`;
    })
    promises.push(new Promise((resolve, reject) => {
      uni.request({
        url: `https://tushuoit.com/api/ju/travel_share/delete_imgs/by_id?id=${travelData.id}${deleteUrls}`,
        method: 'POST',
        success: resolve,
        fail: reject
      });
    }));
  }

  // 更新内容请求
  if (content.value != travelData.report_content) {
    console.log("更新内容请求");
    promises.push(new Promise((resolve, reject) => {
      uni.request({
        url: `https://tushuoit.com/api/ju/travel_share/update_content/by_id?id=${travelData.id}&content=${encodeURIComponent(content.value)}`,
        method: 'POST',
        success: resolve,
        fail: reject
      });
    }));
  }

  // 等待所有请求完成
  Promise.all(promises)
    .then(() => {
      uni.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 2000,
        success: () => {
          uni.navigateBack();
        }
      });
    })
    .catch(err => {
      console.error("保存失败:", err);
      uni.showToast({
        title: '保存失败',
        icon: 'none',
        duration: 2000,
        success: () => {
          uni.navigateBack();
        }
      });
    });
  
}



function uploadPhoto() {
    for (let i = 0; i < photos.value.length; i++) {
    if (photos.value[i].status == "ready") {
        console.log("uploadPhoto:", photos.value[i]);
        photos.value[i].status = "uploading";
        photos.value[i].progress = 0;
        const uploadTask = uni.uploadFile({
        url: 'https://tushuoit.com/api/ju/deepseek/upload',
        filePath: photos.value[i].photo,
        name: 'file',
        formData: {
            apiKey: "juxianwenlv"
        },
        success: res => {
            const data = JSON.parse(res.data);
            console.log("uploadPhoto success:", data);
            photos.value[i].url = data.data.url;
            photos.value[i].status = "uploaded";
            photos.value[i].upload_progress = null;
            console.log("uploadPhoto success:", photos.value[i]);
        },
        fail: () => {
            photos.value[i].status = "failed";
            console.log("uploadPhoto fail:", photos.value[i]);
            photos.value[i].upload_progress = "上传失败";
        },
        complete: () => {
            console.log("uploadPhoto complete:", photos.value[i]);
        }
        });
        uploadTask.onProgressUpdate((res) => {
        console.log('上传进度' + res.progress);
        console.log('已经上传的数据长度' + res.totalBytesSent);
        console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
        photos.value[i].upload_progress = "上传中:" + res.progress + "%";
        });
    }
    }
}

function addPhoto(index) {
    console.log("addPhoto index:", index);
    uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: res => {
        console.log("addPhoto:", res.tempFilePaths.length);
        console.log("addPhoto photos:", photos.value.length);
        photos.value[index] = {photo:res.tempFilePaths[0], status:"ready", url:"", upload_progress:"准备上传"};
        if (index < 2) {
            photos.value.push(null);
        }
        uni.compressImage({
            src: res.tempFilePaths[0],
            quality: 80,
            compressedWidth: 1280,
            format: 'jpeg',
            success: (compressRes) => {
              console.log("compressRes:", compressRes);
              photos.value[index].photo = compressRes.tempFilePath;
            },
            fail: (err) => {
              console.error('Image compression failed:', err);
              // Fallback to original image if compression fails
              photos.value[index].photo = res.tempFilePaths[0]; 
            },
            complete: () => {
              uploadPhoto();
            }
        });
        checkChanged();
    }
    });
}

function removePhoto(index) {
    photos.value.splice(index, 1);
    if (photos.value.length == 0) {
        photos.value.push(null);
    }
    if (photos.value.length < 3 && photos.value.lastIndexOf(null) == -1) {
        photos.value.push(null);
    }
    checkChanged();
}

function loadJournalDataById(travel_id) {
/**
  "data": {
"id": 11,
"user_id": "",
"report_content": "【莒县24h｜在山东小城遇见慢时光】  \n\n清晨的莒县像被阳光吻过的水墨画——古城墙的砖缝里钻出倔强的小野花，浮来山脚下卖豆腐脑的大爷掀开木桶，白雾混着豆香飘进青石板巷弄。我蹲在千年银杏树下数它的皱纹，风一吹，金黄的叶子就簌簌落进我的拿铁里。  \n\n午后溜达到莒国古城，朱漆廊柱下穿汉服的小姐姐们正在拍短视频，无人机掠过屋脊时惊起一群麻雀。最惊喜是转角遇到现烤的周姑子戏饼，焦糖色的糖壳咔嚓裂开，芝麻馅烫得直哈气也舍不得吐。  \n\n当暮色给沭河披上金纱，当地人拎着小马扎到河边钓鱼。有个戴草帽的大叔递给我半块烤地瓜：\"尝尝，俺们这儿土里长的比蜜甜！\"  \n\n原来慢生活不用去江南找，山东小城的烟火气里藏着最治愈的浪漫～  \n（评论区蹲一个你的宝藏小城故事✨）",
"img_urls": [],
"is_active": true,
"created_at": "2025-04-10T11:36:04",
"updated_at": "2025-04-10T11:36:04"
}
  */
  uni.showLoading({
      title: 'Loading...'
    });
  uni.request({
  url: `https://tushuoit.com/api/ju/travel_share/get_travel/by_id?id=${travel_id}`,
  method: 'GET',
  success: (res) => {
    console.log(res);
    travelData = res.data.data;
    content.value = travelData.report_content;
    photos.value = [];
    travelData.img_urls.forEach(url => {
      photos.value.push({
        // photo: url,
        // upload_progress: 0,
        status: "uploaded",
        url: url
      });
    });
    if (photos.value.length < 3) {
        photos.value.push(null);
    }
    uni.hideLoading();
  },
  fail: (err) => {
    console.log(err);
    uni.hideLoading();
    uni.showToast({
      title: '加载游记失败',
      icon: 'none'
    });
  }
  });

}

</script>
  
<style scoped>
.container {
  /* background-color: #f8f0e3; */
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
}


.content {
  flex: 1;
  width: 100%;
}

.content-input {
    /* height: calc(100vh - 640rpx); */
  width: calc(100% - 60rpx);
  height: calc(100% - 60rpx);
  background-color: #fff;
  padding: 30rpx;
  font-size: 30rpx;
}

.bottom-area {
    display: flex;
    flex-direction: column;
    margin-top: 30rpx;
    /* background-color: #018ac7; */
    /* height: 500rpx; */
    /* height: calc(calc(100vw / 3)+200rpx); */
    width: 100%;
}

.photo-grid {
  display: flex;
  flex-direction: row;
  /* flex-wrap: wrap; */
  gap: 10rpx;
}

.scroll-view-horizontal {
  white-space: nowrap;
  width: 100%;
}

.photo-item {
    /* display: inline-block; */
    position: relative;
  background-color: #fff;
  width: calc(33% - 30rpx);
  height: calc(33vw - 30rpx);
  /* line-height: calc(33vw - 30rpx); */
  margin-left: 15rpx;
  /* aspect-ratio: 1/1; */
  border-radius: 10rpx;
}

.photo-preview {
  width: 100%;
  height: 100%;
  border-radius: 8px;
  /* line-height: calc(34vw); */
  object-fit: cover;
}

.photo-placeholder {
  width: 100%;
  height: 100%;
  /* line-height: calc(34vw); */
  background-color: #f9f5f0;
  border: 1px dashed #d9b38c;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  border-radius: 8px;
}
.uploading-indicator {
  
  font-size: 12px;
  color: #ff4d4f;
  background-color: rgba(0, 0, 0, 0.5);
}

.plus-icon {
  font-size: 24px;
  color: #d9b38c;
  margin-bottom: 4px;
}

.photo-progress {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.photo-delete {
  position: absolute;
  top: -8px;
  right: -8px;
  width: 22px;
  height: 22px;
  background-color: rgba(255, 0, 0, 0.7);
  color: white;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.delete-icon {
  font-size: 16px;
}

.action-buttons {
  display: flex;
  /* justify-content: center; */
  align-items: center;
  justify-content: space-between;
  /* background-color: #f00; */
  height: 150rpx;
  padding: 20rpx;
  /* width: 100%; */
}

.cancel-btn {
  width: calc(50% - 20rpx);
  height: 100rpx;
  border-radius: 10rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  /* background-color: #fff; */
  background-color: chocolate;
  color: #FFF;
}

.publish-btn {
  width: calc(50% - 20rpx);
  height: 100rpx;
  border-radius: 10rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  /* margin-left: 20rpx; */
  background-color: #018ac7;
  color: #fff;
}

.back-btn {
  position: absolute;
  left: 20rpx;
  top: 20rpx;
}







</style>
  